package com.bamboo.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.bamboo.eduservice.entity.EduSubject;
import com.bamboo.eduservice.entity.SubjectData;
import com.bamboo.eduservice.service.EduSubjectService;
import com.bamboo.servicebase.exceptionhandler.BambooException;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020-07-04
 */
public class SubjectListener extends AnalysisEventListener<SubjectData> {

    private EduSubjectService subjectService;

    public SubjectListener() {
    }

    public SubjectListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new BambooException(20001, "文件数据为空");
        }
        String title = subjectData.getPrimary();

        // 判断一级分类是否存在
        EduSubject oneSubject = subjectService.existOneSubject(title);
        if (oneSubject == null) {
            oneSubject = new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(title);
            subjectService.save(oneSubject);
        }

        // 判断二级分类是否存在
        String pid = oneSubject.getId();
        EduSubject twoSubject = subjectService.existTwoSubject(title, pid);
        if (twoSubject == null) {
            twoSubject = new EduSubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(subjectData.getSecondary());
            subjectService.save(twoSubject);
        }


    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }


}
